package com.huhao.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class CyclicBarrierExample {
//    /**
//     * 屏障数是5
//     * 等ready了5个后，再连续执行5个continue，在等ready5个，在执行5个continue
//     */
//    private static CyclicBarrier barrier = new CyclicBarrier(5);

    /**
     * 屏障数是5
     * 等ready了5个后，执行callback，再连续执行5个continue，在等ready5个，执行callback，在执行5个continue
     */
    private static CyclicBarrier barrier = new CyclicBarrier(5, () -> {
        log.error("callback is running");
    });

    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int threadNum = i;
            Thread.sleep(1000);
            executor.execute(() -> {
                try {
                    race(threadNum);
                } catch (Exception e) {
                    log.error("exception", e);
                }
            });
        }
        executor.shutdown();
    }

    private static void race(int threadNum) throws Exception {
        //正常业务运行计算可能需要1秒钟，模拟线程睡1秒
        Thread.sleep(1000);
        log.info("{} is ready", threadNum);
        //ready之后调用await方法，表示准备好了
        barrier.await();

//        try {
//            barrier.await(2000, TimeUnit.MILLISECONDS);
//        } catch (BrokenBarrierException | TimeoutException e) {
//            log.warn("BarrierException", e);
//        }

        log.info("{} is continue", threadNum);

    }
}
